#include<unistd.h>
#include<stdio.h>
#include<sys/file.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <errno.h>
#include<string.h>


extern int errno ;

int main() {
  int fd = open("a.txt", O_CREAT| O_RDWR);
  pid_t ret = fork();

  if (ret == 0) {
    // 子进程直接获取exclusive锁
    printf("child try get ex lock.\n");
    if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
        printf("lock ex failed.\n");
    } else {
        printf("child get ex lock.\n");
    }
    printf("child sleep 10s.\n");
    sleep(15);
    printf("child exit.\n");
  } else {
    // 父进程休眠1秒后尝试获取share锁
    sleep(1);
    if (flock(fd, LOCK_SH) != 0) {
        printf("lock sh failed.\n");
        return 0;
    } else {
        printf("parent get shared lock.\n");
    }
    printf("parent sleep 10s\n");
    sleep(15);
  }

}
